import { Message } from '@arco-design/web-vue';
import { ref } from 'vue';
const env = import.meta.env;
const websocketURL = env.VITE_WEBSOCKET_URL;

let flag: NodeJS.Timer;
export default function useWebSocket() {
  const token = localStorage.getItem('token') as string;
  const receiveMsg = ref(); //服务器返回的数据
  const connect = () => {
    const socket = new WebSocket(
      `${websocketURL}/hr/workbench/communication/record/ws`,
      token
    );
    console.log('websocket', socket);
    socket.onopen = function (e) {
      console.log('连接服务器成功');
    };

    socket.onclose = function (e) {
      // console.log('服务器关闭');
    };
    socket.onerror = function (e: Event) {
      // console.log('连接出错123', e);
      throw new Error('连接出错', { cause: e as unknown });
    };
    // 接收服务器的消息
    socket.onmessage = function (e) {
      const res = JSON.parse(e.data);
      if (res.code === 200) {
        receiveMsg.value = res.data;
      }
      // console.log('接收', res);
    };
    return socket;
  };
  return {
    connect,
    receiveMsg
  };
}

export function pingpong(ws: WebSocket) {
  //
  flag = setInterval(() => {
    ws.send(
      JSON.stringify({
        type: 0,
        content: ''
      })
    );
  });
}
